import { NextRequest, NextResponse } from 'next/server';
import { initializeDatabase, getSessions, createSession, Session } from '@/lib/database';
import { withCors } from '@/lib/cors';

// 初始化数据库
let dbInitialized = false;
async function ensureDatabaseInitialized() {
  if (!dbInitialized) {
    await initializeDatabase();
    dbInitialized = true;
  }
}

// GET /api/sessions - 获取会话列表
async function handleGET(request: NextRequest) {
  try {
    await ensureDatabaseInitialized();

    const { searchParams } = new URL(request.url);
    const chatflowId = searchParams.get('chatflowId');
    const userId = searchParams.get('userId');
    const status = searchParams.get('status');

    const sessions = await getSessions(
      chatflowId || undefined,
      userId || undefined,
      status || undefined
    );

    return NextResponse.json({ sessions });
  } catch (error) {
    console.error('获取会话列表失败:', error);
    return NextResponse.json(
      { error: '获取会话列表失败' },
      { status: 500 }
    );
  }
}

// POST /api/sessions - 创建新会话
async function handlePOST(request: NextRequest) {
  try {
    await ensureDatabaseInitialized();

    const body = await request.json();
    const { chatflowId, userId } = body;

    if (!chatflowId) {
      return NextResponse.json(
        { error: '缺少必要参数: chatflowId' },
        { status: 400 }
      );
    }

    const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const session: Omit<Session, 'createdAt' | 'updatedAt'> = {
      id: sessionId,
      chatflowId,
      userId,
      startTime: new Date().toISOString(),
      messageCount: 0,
      status: 'active'
    };

    await createSession(session);

    return NextResponse.json({ session });
  } catch (error) {
    console.error('创建会话失败:', error);
    return NextResponse.json(
      { error: '创建会话失败' },
      { status: 500 }
    );
  }
}

// 导出带 CORS 支持的处理器
export const GET = withCors(handleGET);
export const POST = withCors(handlePOST);
